<template>
  <a-modal
    :maskClosable="false"
    :title="id?'修改门店基本信息':'新增门店基本信息'"
    :width="850"
    :visible="showModal"
    :confirm-loading="confirmLoading"
    :ok-type="'primary'"
    @ok="confirmOk"
    @cancel="cancel"
  >
    <a-form :form="form">
      <a-row :gutter="[24,0]">
        <a-col :span="12">
          <a-form-item class="mb-15" label="门店名称" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              class="w-full"
              placeholder="请输入门店名称"
              v-decorator="[
							'name',
							{rules: [{required: true,whitespace: true,message: '请输入门店名称'}]}
						]"
              maxLength="15"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item class="mb-15" label="服务商" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              class="w-full"
              disabled
              placeholder="请输入服务商"
              v-decorator="[
							'supplierName'
						]"
              maxLength="15"
            ></a-input>
          </a-form-item>
        </a-col>
        <!--        <a-col :span="12">-->
        <!--          <a-form-item class="mb-15" label="门店编号" :label-col="labelCol" :wrapper-col="wrapperCol">-->
        <!--            <a-input-->
        <!--              class="w-full"-->
        <!--              disabled-->
        <!--              placeholder="请输入门店编号"-->
        <!--              v-decorator="['storeId']"-->
        <!--              maxLength="15"-->
        <!--            ></a-input>-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
      </a-row>
      <a-row :gutter="[24,0]">
        <a-col :span="12">
          <a-form-item class="mb-15" label="联系人" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              class="w-full"
              placeholder="请输入联系人"
              v-decorator="[
							'contactName',
							{rules: [{required: true,whitespace: true,message: '请输入联系人'}]}
						]"
              maxLength="15"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item class="mb-15" label="联系方式" :label-col="labelCol" :wrapper-col="wrapperCol">
            <section class="flex">
              <a-input
                class="w-full"
                placeholder="请输入联系方式"
                v-decorator="[
							'telephone',
							{rules: [{required: true,whitespace: true,message: '请输入联系方式',validator: $utils.phoneValidator}]}
						]"
                :min="0"
                maxLength="64"
              ></a-input>
              <a-tooltip placement="top" :title="`联系方式可以输入多个，用逗号隔开`">
                <a-icon class="mt-10 ml-5 warning-color" type="exclamation-circle"/>
              </a-tooltip>
            </section>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="[24,0]">
        <a-col :span="12">
          <a-form-item class="mb-15" label="门店联系人手机号" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-input
              class="w-full"
              placeholder="请输入门店联系人手机号"
              v-decorator="[
							'contactPhoneNumber',
							{rules: [{required: true,whitespace: true,message: '请输入门店联系人手机号',validator: $utils.purePhoneValidator}]}
						]"
              :min="0"
              maxLength="18"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item class="mb-15" label="所在城市" :label-col="labelCol" :wrapper-col="wrapperCol">
            <!--            <a-cascader-->
            <!--              class="mr-24"-->
            <!--              placeholder="请选择所在城市"-->
            <!--              :options="cityList"-->
            <!--              v-decorator="[-->
            <!--							'cityId',-->
            <!--							{rules: [{required: true,message: '请选择所在城市'}]}-->
            <!--						]"-->
            <!--              @change="cascaderChange"-->
            <!--            >-->
            <!--            </a-cascader>-->
            <SelectCity
              v-if="showModal"
              class="mr-24"
              ref="selectCity"
              placeholder="请选择城市"
              :options="{allowClear: true}"
              :cityKey="'code'"
              v-decorator="[
								'cityCode',
								{rules: [{required: true,message: '请选择所在城市'}]}
							]"
              @change="cityChange"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="[24,0]">
        <a-col :span="24">
          <a-form-item class="mb-15" label="详细地址" :label-col="{span:4}" :wrapper-col="{span:20}">
            <a-tooltip placement="top" title="请点击选择地址">
              <section class="flex" @click="setMapPoint({...addressPoint,type:2})">
                <a-input
                  disabled
                  placeholder="请点击选择地址"
                  v-decorator="[
              'address',
              {rules: [{required: true,whitespace: true,message: '请点击选择地址'}]}
            ]"
                  maxLength="256"
                ></a-input>
                <img
                  class="pin cursor-pointer"
                  :src="pin"
                >
              </section>
            </a-tooltip>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="[24,0]">
        <a-col :span="24">
          <a-form-item class="mb-15 shop-photo" label="门店照片与其他相关资料" v-if="showModal">
            <span class="num">{{ fileList.length }}/10</span>
            <multipleShowList ref="fileList" :scene="7" :fileLength="10" @uploadSuccess="uploadAvatarSucces"
                              @removeFile="removeFile"/>
            <a-input
              type="hidden"
              placeholder="请上传门店照片与其他相关资料"
              v-decorator="[
              'fileList',
              {rules: [{required: true,message: '请上传门店照片与其他相关资料'}]}
            ]"
              maxLength="200"
            ></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <AddressComponent :city="city" ref="AddressComponent" @uploadPoint="uploadPoint"></AddressComponent>
  </a-modal>
</template>
<script>
import multipleShowList from '@/components/Upload/multipleShowList'
import {getStoreDetail, editStoreSubject, addStore} from '@/api/store'
import {getAllProvinces} from '@/api/geography'
import AddressComponent from '@/views/operationInfo/supplierManagement/AddressComponent'

export default {
  name: 'StoreSituationInfo',
  props: {
    name: { //服务商
      type: String,
      default: ''
    }
  },
  components: {multipleShowList, AddressComponent},
  data() {
    return {
      labelCol: {span: 8},
      wrapperCol: {span: 16},
      showModal: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      fileList: [],
      editData: null,
      cityList: [],
      addressPoint: null,
      info: null,
      cityId: null,
      pin: require('@/assets/icons/pin.png'),
      id: null,
      city: undefined
    }
  },
  created() {
    this.id = this.$route.params.id
    this.allProvinces()
  },
  methods: {
    cityChange(cityObj) {
      this.city = cityObj ? cityObj.name : undefined
      this.cityId = cityObj ? cityObj.id : cityObj
    },
    uploadPoint(data) {
      this.addressPoint = data
      this.form.setFieldsValue({address: data.address})
    },
    setMapPoint(data) {
      this.$refs.AddressComponent.getAddressValue(data)
    },
    allProvinces() {
      getAllProvinces().then(data => {
        data.forEach(item => {
          item.label = item.name
          item.value = item.code
          item.children = item.cities.map(e => ({
            label: e.name,
            value: e.id,
            id: e.id
          }))
        })
        this.cityList = data
      })
    },
    getData(data) {
      if (data) {
        this.editData = data
        this.loading = true
        this.showModal = true
        getStoreDetail({storeId: data.id}).then(res => {
          const {imgUrl, latitude, longitude, cityId, cityCode, address} = res
          const imgUrlarr = imgUrl ? imgUrl.indexOf(',') ? imgUrl.split(',') : [imgUrl] : undefined
          this.info = res
          this.$nextTick(() => {
            if (imgUrlarr && imgUrlarr.length) {
              const fileList = imgUrlarr.map(item => ({
                name: 'image.png',
                status: 'done',
                url: item,
                uid: this.$utils.uuid()
              }))
              this.fileList = fileList
              this.$refs.fileList.setFileList(fileList)
              this.form.setFieldsValue({fileList})
            }
            // if (res.provinceCode) {
            //   res.cityId = [res.provinceCode, res.cityId] //城市
            // }
            this.addressPoint = {latitude, longitude, address}
            this.cityId = cityId
            this.city=res.cityName
            this.$refs.selectCity.searchCityData(cityCode, {
              key: cityCode,
              label: cityCode + '-' + res.cityName
            })
            this.form.setFieldsValue({storeId: this.id, supplierName: this.name, ...res})
          })
        }).finally(() => {
          this.loading = false
        })
        return false
      }
      this.showModal = true
      this.$nextTick(() => {
        this.cityId = null
        this.form.setFieldsValue({storeId: this.id, supplierName: this.name})
      })
    },
    removeFile(data) {
      this.fileList.splice(this.fileList.findIndex(item => item.uid === data.uid), 1)
    },
    uploadAvatarSucces(data) {
      this.fileList = data
      this.form.setFieldsValue({fileList: data})
    },
    orderValidator(rule, value, callback) {
      const amount = value && value.trim()
      const isAmount = /^([1-9]\d*|[0]{1,1})$/
      if (amount === '') {
        callback()
      }
      if (amount && !isAmount.test(amount)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    },
    amountValidator(rule, value, callback) {
      const amount = value && value.trim()
      const isAmount = /^(\+)?\d+(\.\d{1,2})?$/
      if (amount === '') {
        callback()
      }
      if (amount * 1 === 0 || amount && !isAmount.test(amount)) {
        callback(new Error('请输入正数且保留两位小数'))
      } else {
        callback()
      }
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const {editData, cityId} = this
          const imgUrl = this.fileList.map(item => item.url)
          if (!imgUrl.length) return this.$message.warning('请上传门头照片与其他相关资料')
          const id = editData && editData.id ? editData.id : undefined
          const {longitude, latitude} = this.addressPoint
          const fun = id ? editStoreSubject : addStore
          fun({
            id: id,
            ...this.$utils.trimValue(values),
            longitude,
            latitude,
            cityId,
            vendorId: this.id,
            imgUrl: imgUrl.join(',')
          }).then(() => {
            this.$message.success(id ? '修改成功！' : '新建成功！')
            this.$emit('upload')
            this.getData()
            this.cancel()
          })
        }
      })
    },
    cancel() {
      this.confirmLoading = false
      this.addressPoint = null
      this.info = null
      this.editData = null
      this.fileList = []
      this.form.resetFields()
      this.showModal = false
    }
  }
}
</script>
<style lang="less" scoped>
.shop-photo {
  position: relative;

  .num {
    position: absolute;
    top: -39px;
    font-size: 14px;
    font-weight: bold;
    left: 174px;
    color: #999;
  }
}

.pin {
  margin: -10px 0 0 5px;
  height: 45px;
}
</style>
